import React, { PureComponent, Fragment } from 'react';
import PropTypes from 'prop-types';
import withRouter from 'umi/withRouter';
import { connect } from 'dva';
import { MyLayout } from '@/components';
import { Layout } from 'antd';
import Error from '../pages/404';
import { pathMatchRegexp } from '@/utils';
import NavBar from './NavBar';
import styles from './PrimaryLayout.less';
import { pathExists } from '@/utils/routes';

const { Content } = Layout;
const {
  Sider,
} = MyLayout;

@withRouter
@connect(({ app, loading }) => ({ app, loading }))
class PrimaryLayout extends PureComponent {
  // 点击退出登录
  handleLogout = () => {
    this.props.dispatch({
      type: 'app/logoutEffect',
    });
  };

  render() {
    const { app, location, children } = this.props;
    const {
      theme,
      routeList,
      openKeys,
      user,
      locationPathname,
    } = app;

    const pageExist = pathExists(location.pathname); // 访问不存在的页面则是 false

    const siderProps = {
      theme,
      menus: routeList,
      openKeys,
    };

    const navbarProps = {
      user,
      locationPathname,
      handleLogout: this.handleLogout,
    };

    return (
      <Fragment>
        <Layout>
          <Sider {...siderProps} />
          <div
            className={styles.container}
            id="primaryLayout"
          >
            <NavBar {...navbarProps} />
            {/*<Loader fullScreen={false} spinning={loading.global} />*/}
            <Content className={styles.content}>
              {pageExist? children: <Error location={location} />}
            </Content>
          </div>
        </Layout>
      </Fragment>
    );
  }
}

PrimaryLayout.propTypes = {
  children: PropTypes.element.isRequired,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  app: PropTypes.object,
  loading: PropTypes.object,
};

export default PrimaryLayout;
